#coding=utf-8

from django.shortcuts import render, render_to_response,RequestContext, get_object_or_404,get_list_or_404
from models import Article,FeedSource
from datetime import datetime
from forms import FeedForm
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage     # 分页函数
from django.views.generic import ListView, DetailView

# Create your views here.

def my_pagination(request, queryset, display_amount=25, after_range_num = 5,bevor_range_num = 4):
    #按参数分页
    paginator = Paginator(queryset, display_amount)
    try:
        #得到request中的page参数
        page =int(request.GET.get('page'))
    except:
        #默认为1
        page = 1
    try:
        #尝试获得分页列表
        objects = paginator.page(page)
    #如果页数不存在
    except EmptyPage:
        #获得最后一页
        objects = paginator.page(paginator.num_pages)
    #如果不是一个整数
    except:
        #获得第一页
        objects = paginator.page(1)
    #根据参数配置导航显示范围
    if page >= after_range_num:
        page_range = paginator.page_range[page-after_range_num:page+bevor_range_num]
    else:
        page_range = paginator.page_range[0:page+bevor_range_num]
    return objects,page_range

class BaseListView(ListView):
    template_name = 'index.html'
    context_object_name = 'article_list'
    
    def get_context_data(self,**kwargs):
        objects, page_range= my_pagination(self.request, self.object_list)
        kwargs['articles']= objects
        kwargs['page_range']= page_range
        return super(BaseListView, self).get_context_data(**kwargs)
    
class IndexView(BaseListView):
    queryset= Article.objects.filter(create_date= datetime.today())
    
class AllView(BaseListView):
    queryset= Article.objects.all()
    
class SiteView(BaseListView):
    template_name = 'index.html'
    context_object_name = 'article_list'
    def get_queryset(self):
        # print self.args[0]
        objs=get_list_or_404(Article, name =self.args[0])
        # print objs
        return objs                           

def welcome(req):
    # pass
    return HttpResponse('welcome!')

def form(req):
    if req.method=='POST':
        form=FeedForm(req.POST)
        if form.is_vilid():
            feed_obj=FeedSource.objects.create()
            feed_obj.name=form.cleaned_date['name']
            feed_obj.link=form.cleaned_data['link']
            feed_obj.save()
            return HttpResponse(u'录入成功')
    else:
        form=FeedForm()
    return render_to_response("form.html",{"form": form })
